#coding:utf8
'''
Created on 2010-9-23

@author: TooNTonG
'''
import shelve
from linux import *


remote = RemoteFiles()
local = LocalFiles()
db = shelve.open('%s/%d.shelve' % (TMP, int(userId)))
if db.has_key('local') and db.has_key('remote'):
    print 'load from shelve'
    local, remote = db['local'], db['remote']
else:
    print 'load api server.'
    make_remote(token, remote)
    make_local(root, local)
db.close()



def difflocal(glocal):
    '''比较本地目录文件是否有变化，过滤去新增的 与 修改的文件'''
    result_add = [] #比上一次扫描，新增的文件夹/文件 或修改了的文件
    result_sub = [] #本地比上一次扫描，减少的文件
    tmpLocal = LocalFiles()
    def _walk_calbak(agrs, dirname, filenamelst):
        vdirname = encoding(dirname[root.__len__():].replace('\\', '/'))
        if vdirname.startswith(r'/.'):return
        for fname in filenamelst:
            if fname.startswith('.'):continue
            item = format_local_obj(dirname, vdirname, fname)
            agrs.append(item)
            if not glocal.has_vpath(item['vpath']):
                result_add.append(item)
                continue
            last = glocal.get(item['vpath'])
            # 1).先比较修改时间
            if last['modTime'] != item['modTime'] or \
               last['createdTime'] != item['createdTime'] or\
               last['size'] != item['size']:
                result_add.append(item)
    os.path.walk(root, _walk_calbak, tmpLocal)
    for item in glocal.items():
        if tmpLocal.has_vpath(item['vpath']):
            continue
        else: result_sub.append(item)
    return result_add, result_sub
def _updatefile(m, l):
    fp = open(tolocalpath(root + m['vpath']), 'rb')
    contents = fp.read()
    fp.close()
    sha1 = hashlib.sha1(contents).hexdigest()
    if sha1 == m['sha1']:
        print 'sha1 一样，不上传'
        del contents
        return True
    res = kuaiPanApi.updateFile(token, m['fileId'], m['fileVer'], contents)
    del contents
    m['fileVer'] = res['fileVer']
    m['sha1'] = res['sha1']
    return True
    
def _sync_up_add(addlst):
    ''' 确认是新增文件，执行上行新增'''
    addlst.sort(LocalFiles.cmp)
    for l in addlst:
        if l['type'] == 'folder' or not remote.has_vpath(l['vpath']):
            assert not local.has_vpath(l['vpath'])
            print 'new folder.', l['name']
            if up_new(l, remote):
                local.append(l)
            continue
        m = remote.get(l['vpath'])
        assert m and m['type'] == 'file' and local[l['vpath']]
        if _updatefile(m, l):
            l['fileId'] = m['fileId']
            l['fileVer'] = m['fileVer']
            l['sha1'] = m['sha1']
            local.append(l)
        
               
def _sync_up_del(sublst):
    ''' 处理上行删除'''
    pass
def sync_local(newAdd, newDel):
    assert isinstance(newAdd, list) and isinstance(newDel, list)
    print newAdd, newDel
    if newAdd and not newDel:
        #本地有新增，没减
        _sync_up_add(newAdd)
    elif newDel and not newAdd:        
        _sync_up_del(newDel)    
    else:
        #同时有增、删，可能是改名与移动。
        assert False
import time
def main():
    same_up = sync_up(local, remote)
    same_down = sync_down(local, remote)
    assert len(same_up) ==  len(same_down)
    sync_same(local, remote, same_down)
    print 'begin diff local.'
    while True:
        newAdd, newDel = difflocal(local)        
        if not newAdd and not newDel:
            time.sleep(2); continue    
        sync_local(newAdd, newDel)
        
        
if __name__ == '__main__':
    main()
def myhandle(n, e):
    print n , e
    print 'signal....'
    
import signal
signal.signal(signal.SIGINT, myhandle)
signal.signal(signal.SIGTERM, myhandle)
signal.signal(2, myhandle)



import atexit
@atexit.register
def exit_handle():
    print 'app close'
    dbase = shelve.open('%s/%d.shelve' % (TMP, int(userId)))
    dbase['local'] = local
    dbase['remote'] = remote
    dbase.close()